/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.persistence.service.EmployeeService;
import com.lmx.repoDomain.tmodel.StaffWorkTimeSetting;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(StaffWorkTimeSetting.class)
@Component
public class StaffWorkTimeSettingRepository extends BaseRepository<StaffWorkTimeSetting> {

	@Autowired
	protected EmployeeService employeeService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(StaffWorkTimeSetting.class);
	}

	@Override
	@JsonApiSave
	public StaffWorkTimeSetting save(StaffWorkTimeSetting record) {
		// remark(0-52) 存放复制的目标周 0 不复制 判断 是否复制
		if (record.getTarget() != null && !"0".equals(record.getTarget()) && record.getTarget().matches("\\d+")
				&& record.getResource() != null && !"0".equals(record.getResource()) && record.getResource().matches("\\d+")) {
			int resourceWeekIndex = Integer.parseInt(record.getResource());
			int targetWeekIndex = Integer.parseInt(record.getTarget());
			if (resourceWeekIndex >= 1 && resourceWeekIndex <= 52 && targetWeekIndex >= 1 && targetWeekIndex <= 52) {
				employeeService.copyStaffTimeSetting(record.getStaffs(), resourceWeekIndex, targetWeekIndex);
			}
		} else {
			record = super.save(record);// 存储
		}
		return record;
	}
}
